const express = require('express')
const multer = require('multer')
const boom = require('boom')

const { decode } = require('../../utils')
const { UPLOAD_PATH } = require('../../utils/constant')
const Result = require('../../models/Result')
const Book = require('../../models/Book')
const { insertBook, getBook, updateBook, getCategory, listBook, deleteBook } = require('../../services/book')

const router = express.Router()

router.post(
  '/upload',
  multer({
    dest: `${UPLOAD_PATH}/book`
  }).single('file'),
  function(req, res, next) {
    console.log(req.file)
    if (!req.file || req.file.length === 0) {
      new Result('上传电子书失败').fail(res)
    } else {
      // console.log('req.file', req.file)
      const book = new Book(req.file)
      // console.log(book, 'bool')
      // new Result('上传成功').success(res)
      book.parse()
        .then(book => {
          // new Result('上传成功').success(res)
          new Result(book.toJson(), '上传成功').success(res)
        })
        .catch((err) => {
          next(boom.badImplementation(err))
          // book.reset()
        })
    }
  }
)

router.post(
  '/create',
  function (req, res, next) {
    const book = new Book(null, req.body)
    const myDecode = decode(req)
    if (myDecode && myDecode.username) {
      book.username = decode.username
    }
    updateBook(book).then(() => {
      console.log('------------')
      new Result('添加电子书成功').success(res)
    }).catch((err) => {
      next(boom.badImplementation(err))
    })
  }
)

router.get('/get', function (req, res, next) {
  const { fileName } = req.query
  if (!fileName) {
    next(boom.badRequest(new Error('参数不能为空')))
  } else {
    getBook(fileName).then((book) => {
      new Result(book, '获取图书信息成功').success(res)
    }).catch((err) => {
      next(boom.badImplementation(err))
    })
  }
})

router.post(
  '/update',
  function (req, res, next) {
    const book = new Book(null, req.body)
    const myDecode = decode(req)
    if (myDecode && myDecode.username) {
      book.username = decode.username
    }
    updateBook(book).then(() => {
      new Result('添加电子书成功').success(res )
    }).catch((err) => {
      next(boom.badImplementation(err))
    })
  }
)

router.get('/category', function (req, res, next) {
  getCategory().then((category) => {
    new Result(category, '获取分类成功').success(res)
  }).catch((err) => {
    next(boom.badImplementation(err))
  })
})

router.get('/list', function (req, res, next) {
  listBook(req.query).then((data) => {
    new Result(data, '获取分类成功').success(res)
  }).catch((err) => {
    next(boom.badImplementation(err))
  })
})

router.post('/delete', function (req, res, next) {
  const { fileName } = req.body
  deleteBook(fileName).then(() => {
    new Result('删除图书信息成功').success(res)
  }).catch(err => {
    next(boom.badImplementation(err))
  })
})

module.exports = router
